package com.intct.hbase.ddl.impl;

import com.intct.hbase.ddl.AbsDDLSerivce;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gufg
 * @since 2025-09-29 10:38
 */
public class CreateTable extends AbsDDLSerivce {
    private String namespace;
    private String tName;

    private List<String> familyList;

    public CreateTable(String namespace, String tName, List<String> familyList) {
        this.namespace = namespace;
        this.tName = tName;
        this.familyList = familyList;
    }
    @Override
    public void execCommand(Admin admin) {
        // 创建一个tableName对象
        TableName tableName = TableName.valueOf(namespace, tName);

        try {
            // 判断表是否存在，不存在创建
            // create 'ns:t1',{NAME => 'f1', VERSIONS => 4}
            if (!admin.tableExists(tableName)) {
                // 表描述
                TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);

                List<ColumnFamilyDescriptor> columnFamilyDescriptorList = new ArrayList<>();

                for (String family : familyList) {
                    // 切分
                    String[] fv = family.split(":");

                    // 列族描述
                    ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(fv[0].getBytes());

                    // 设置版本
                    columnFamilyDescriptorBuilder.setMaxVersions(Integer.parseInt(fv[1]));

                    columnFamilyDescriptorList.add(columnFamilyDescriptorBuilder.build());
                }

                // 设置列族信息
                tableDescriptorBuilder.setColumnFamilies(columnFamilyDescriptorList);

                // 预分区
                byte[][] splitKeys = new byte[4][];
                splitKeys[0] = "10".getBytes();
                splitKeys[1] = "20".getBytes();
                splitKeys[2] = "30".getBytes();
                splitKeys[3] = "40".getBytes();

                // 创建表
                admin.createTable(tableDescriptorBuilder.build(), splitKeys);
            }
        } catch (IOException e) {
            System.out.println("创建表失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        List<String> familys = new ArrayList<>();
        familys.add("f1:3");
        familys.add("f2:3");
        familys.add("f3:5");
        familys.add("f4:5");
        familys.add("f5:5");
        new CreateTable("intct85", "t3_api", familys).start();
    }
}
